package com.logos.musicframe.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.logos.musicframe.constant.RedisConstant;
import com.logos.musicframe.converter.SongsConverter;
import com.logos.musicframe.entity.Songs;
import com.logos.musicframe.entity.SongsLiked;
import com.logos.musicframe.enums.IsLikedEnum;
import com.logos.musicframe.mapper.SongsLikedMapper;
import com.logos.musicframe.mapper.SongsMapper;
import com.logos.musicframe.req.SongsReq;
import com.logos.musicframe.resp.SongsResp;
import com.logos.musicframe.service.FileService;
import com.logos.musicframe.service.SongsService;
import com.logos.musicframe.utils.RedisUtil;
import com.logos.musicframe.utils.UserInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 歌曲信息主表(Songs)表服务实现类
 *
 * @author rose
 * @since 2025-05-29 13:17:32
 */
@Service("songsService")
@Slf4j
public class SongsServiceImpl implements SongsService {

    @Autowired
    private SongsMapper songsMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private FileService fileService;

    @Autowired
    private SongsLikedMapper songsLikedMapper;

    @Autowired
    private UserInfoUtil userInfoUtil;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Songs queryById(Integer id) {
        return this.songsMapper.queryById(id);
    }

    /**
     * 新增数据
     *
     * @param songs 实例对象
     * @return 实例对象
     */
    @Override
    public Songs insert(Songs songs) {
        this.songsMapper.insert(songs);
        return songs;
    }

    /**
     * 修改数据
     *
     * @param songs 实例对象
     * @return 实例对象
     */
    @Override
    public Songs update(Songs songs) {
        this.songsMapper.update(songs);
        return this.queryById(songs.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.songsMapper.deleteById(id) > 0;
    }

    @Override
    public List<SongsResp> queryAll(Integer userId) {
        // 先检查缓存中是否存在
        if (redisUtil.exist(RedisConstant.ALL_SONG)) {
            String songsRespListStr = redisUtil.get(RedisConstant.ALL_SONG);
            List<SongsResp> songsRespList = JSONObject.parseArray(songsRespListStr, SongsResp.class);
            log.info("songsService.queryAll.Cache.Hit:{}", songsRespList);
            return songsRespList;
        }
        List<Songs> sonsList = songsMapper.queryByCondition(new Songs());
        if (sonsList == null || sonsList.size() == 0) {
            return null;
        }
        // 取前十条
        sonsList = sonsList.stream().limit(10).toList();
        List<SongsResp> songsRespList = querySongsWithLike(sonsList);
        // 将结果存入缓存
        redisUtil.setNx(RedisConstant.ALL_SONG, JSONObject.toJSONString(songsRespList), Long.valueOf(RedisConstant.EXPIRE_TIME_THREE_MINUTES));
        return songsRespList;
    }

    @Override
    public List<SongsResp> queryByCondition(Songs condition) {
        List<Songs> sonsList = songsMapper.queryByCondition(condition);
        if (sonsList == null || sonsList.size() == 0) {
            return null;
        }
        List<SongsResp> songsRespList = querySongsWithLike(sonsList);
        return songsRespList;
    }

    private List<SongsResp> querySongsWithLike(List<Songs> sonsList) {
        // 取前十条
        sonsList = sonsList.stream().limit(10).toList();
        List<SongsResp> songsRespList = new ArrayList<>();
        Integer userId = userInfoUtil.getUserId();
        // 把该用户喜欢的歌曲从数据库中都给查出来
        SongsLiked songsLiked = new SongsLiked().setUserId(userId);
        List<SongsLiked> songsLikedList = songsLikedMapper.queryByCondtion(songsLiked);
        if(songsLikedList == null || songsLikedList.isEmpty()){
            return Collections.emptyList();
        }
        Set<Integer> isLikedSet= songsLikedList.stream().map(SongsLiked::getSongId).collect(Collectors.toSet());
        for (Songs songs : sonsList) {
            SongsResp songsResp = SongsConverter.INSTANCE.convertEntityToResp(songs);
            // 数据库中有存在则存在
            if (isLikedSet.contains(songs.getId())) {
                songsResp.setIsLiked(IsLikedEnum.LIKED.isDesc());
            }else{
                songsResp.setIsLiked(IsLikedEnum.UN_LIKED.isDesc());
            }
            songsRespList.add(songsResp);
        }
        return songsRespList;
    }

    @Override
    public Boolean uploadSong(SongsReq songsReq) {
        Songs songs = SongsConverter.INSTANCE.convertReqToEntity(songsReq);
        // 设置当前时间
        songs.setCreatedAt(new Date());
        // 上传音乐文件和图片获得url
        // 先处理音乐文件
        File songFile = songsReq.getSongFile();
        if(songFile != null && songFile.exists()){
            String fileUrl = fileService.uploadFile(songFile);
            songs.setFilePath(fileUrl);
        }
        // 图片上传处理（如果存在）
        File coverImageFile = songsReq.getPicture();
        if (coverImageFile != null && coverImageFile.exists()) {
            String coverImageUrl = fileService.uploadFile(coverImageFile);
            songs.setPicture(coverImageUrl);
        }
        // 歌词文件上传处理（如果存在）
        File lrcFile = songsReq.getLrc();
        if (lrcFile != null && lrcFile.exists()) {
            String lrcUrl = fileService.uploadFile(lrcFile);
            songs.setLrc(lrcUrl);
        }
        // 保存歌曲信息到数据库
        songsMapper.insert(songs);
        // 清空主页歌曲列表缓存
        redisUtil.del(RedisConstant.ALL_SONG);
        return true;
    }
}
